package org.example;

import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.sql.SQLException;

public class DataMigration {
    private DatabaseManager dbManager;
    private ForeignKeyService foreignKeyService;

    public DataMigration(DatabaseManager dbManager) {
        this.dbManager = dbManager;
        this.foreignKeyService = new ForeignKeyService(dbManager);
    }

    public List<Map<String, Object>> processData(List<Map<String, Object>> data, List<MappingRule> rules) {
        List<Map<String, Object>> processedData = new ArrayList<>();
        
        for (Map<String, Object> row : data) {
            Map<String, Object> newRow = new HashMap<>();
            for (MappingRule rule : rules) {
                String sourceField = rule.getSourceField();
                String targetField = rule.getTargetField();
                Object value = row.get(sourceField);
                
                // 处理外键
                try {
                    Object processedValue = foreignKeyService.processForeignKey(rule, value);
                    newRow.put(targetField, processedValue);
                } catch (SQLException e) {
                    System.err.println("外键处理失败: " + e.getMessage());
                    newRow.put(targetField, null);
                }
            }
            processedData.add(newRow);
        }
        
        return processedData;
    }
}